package com.example.rabc.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 真实的OAuth服务实现类，用于处理OAuth2认证
 */
@Service
public class RealOAuthService {
    
    private static final Logger logger = LoggerFactory.getLogger(RealOAuthService.class);
    
    @Autowired
    private OAuth2AuthorizedClientService authorizedClientService;
    
    /**
     * 验证OAuth2令牌并获取用户信息
     * @param authentication OAuth2认证令牌
     * @return OAuth2用户对象
     */
    public OAuth2User validateAndGetUser(OAuth2AuthenticationToken authentication) {
        try {
            // 获取已授权的客户端
            OAuth2AuthorizedClient authorizedClient = 
                authorizedClientService.loadAuthorizedClient(
                    authentication.getAuthorizedClientRegistrationId(),
                    authentication.getName());
            
            if (authorizedClient == null) {
                logger.warn("No authorized client found for registration ID: {}", 
                           authentication.getAuthorizedClientRegistrationId());
                return null;
            }
            
            // 获取访问令牌
            OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
            logger.info("Access token type: {}", accessToken.getTokenType());
            logger.info("Access token scopes: {}", accessToken.getScopes());
            
            // 获取用户信息
            OAuth2User oauth2User = authentication.getPrincipal();
            logger.info("User name: {}", oauth2User.getName());
            logger.info("User attributes: {}", oauth2User.getAttributes());
            
            return oauth2User;
        } catch (Exception e) {
            logger.error("Error validating OAuth2 token", e);
            return null;
        }
    }
    
    /**
     * 从OAuth2用户获取角色信息
     * @param oauth2User OAuth2用户对象
     * @return 用户角色集合
     */
    public Set<String> getUserRoles(OAuth2User oauth2User) {
        // 根据OAuth提供商返回的用户属性映射角色
        Set<String> roles = new HashSet<>();

        // GitHub示例：根据用户属性映射角色
        String username = oauth2User.getName();
        // 可以根据需要添加更多角色映射逻辑

        // 默认添加用户角色
        roles.add("ROLE_USER");

        // 根据用户属性判断是否为管理员
        Map<String, Object> attributes = oauth2User.getAttributes();
        if (attributes.containsKey("site_admin") && (Boolean) attributes.get("site_admin")) {
            roles.add("ROLE_ADMIN");
        }

        logger.info("Mapped roles for user {}: {}", username, roles);
        return roles;
    }
}